import axios from 'axios'
import { getOnceTokenFn } from '@/api/getOnceToken'
import { getToken, getUserInfo } from '@/utils/auth'

export async function fileUploadInterface(url = '/ser/volunteer/addVolunteerPL', file, keyName = 'file') {
  const userInfo = JSON.parse(getUserInfo('userInfo'))
  const formData = new FormData()
  formData.append(keyName, file)
  formData.append('userId', userInfo.userId)


  const ajax = axios.create({
    withCredentials: true
  })

  const config = {
    headers: {
      'Content-Type': 'multipart/form-data',
      'userToken': getToken(),
      'onceToken': onceToken
    }
  }

  return new Promise((resolve, reject) => {
    ajax.post(process.env.VUE_APP_BASE_API + url, formData, config).then(res => {
      return resolve(res)
    })
  })
}

export function fileUpload(path, fileName) {
  let url = process.env.VUE_APP_BASE_API + path;
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';
  xhr.onload = function() {
    console.log(xhr.response)
    if (xhr.status === 200) {
      const blob = new Blob([xhr.response]);
      const a = document.createElement('a');
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = fileName;
      a.click();
      window.URL.revokeObjectURL(url);
    }
  };
  xhr.send();
}
